<?php
/**
* @filename source_module.php 2013-11-11 02:10:56x
* @author Huming Xu <huming17@126.com>
* @version 1.0.0
* @copyright DZF (c) 2013, Huming Xu
*/

class ctrl_trade_course extends trade_course{
    public $info_array = array();
	public $page_array = array();
	public $tree_array = array();
    
    static function &instance() {
		static $object;
		if(empty($object)) {
			$object = new self();
		}
		return $object;
	}
        
    /*
	*	取出一条信息
	*/
	public function do_detail($tc_id='') {
		$detail = array();
        $tc_id = isset($_REQUEST['tc_id']) ? $_REQUEST['tc_id'] : '';
		$detail = $this->one_info('trade_course','tc_id',$tc_id);
        //DEBUG 调试输出
        include template('trade/course/detail');
	}
    
	/*
	*  添加系统信息
	*/
	public function do_add() {
        global $_G;
		$issubmit = isset($_REQUEST['issubmit']) && !empty($_REQUEST['issubmit']) ? $_REQUEST['issubmit']:'';
		$trade_course = isset($_REQUEST['trade_course']) && !empty($_REQUEST['trade_course']) ? $_REQUEST['trade_course']:'';
		if('1'==$issubmit){
            //TODO 后端字段校验 根据具体业务逻辑添加
            //DEBUG 判断是否数组字段,如果是数组转换为逗号间隔 字符串存贮
            foreach($trade_course AS $key => $value){
                if(is_array($value) && !empty($value)){
                    $trade_course[$key] = implode(",", $value);
                }
            }
            $trade_course['create_dateline'] = TIMESTAMP;
            $insert_id = $this->add('trade_course',$trade_course);
            if($insert_id){
                showmessage('操作成功','index.php?mod=trade&action=course&do=index');
            }else{
                showmessage('操作失败','index.php?mod=trade&action=course&do=index');
            }
		}else{
			include template('trade/course/add');
		}
	}
    
	/*
	*  编辑系统信息
	*/
	public function do_edit() {
        global $_G;
		$issubmit = isset($_REQUEST['issubmit']) && !empty($_REQUEST['issubmit']) ? $_REQUEST['issubmit']:'';
		$trade_course = isset($_REQUEST['trade_course']) && !empty($_REQUEST['trade_course']) ? $_REQUEST['trade_course']:'';
        $tc_id = isset($_REQUEST['tc_id']) ? $_REQUEST['tc_id'] : '';
        if($tc_id){
            if('1'==$issubmit){
                $trade_course['modify_dateline'] = TIMESTAMP;
                //DEBUG 判断是否数组字段,如果是数组转换为逗号间隔 字符串存贮
                foreach($trade_course AS $key => $value){
                    if(is_array($value) && !empty($value)){
                        $trade_course[$key] = implode(",", $value);
                    }
                }                
                $where = array('tc_id'=>$tc_id);
                $effect_row = $this->edit('trade_course',$trade_course,$where);
                if($effect_row){
                    showmessage('操作成功','index.php?mod=trade&action=course&do=index');
                }else{
                    showmessage('操作失败','index.php?mod=trade&action=course&do=index');
                }
            }else{
                //DEBUG 获取操作对象信息
                $info = $this->one_info('trade_course','tc_id',$tc_id);
                include template('trade/course/edit');
            }
        }else{
            showmessage('请选择编辑对象','index.php?mod=trade&action=course&do=index');
        }
	}
    
	/*
	*  删除系统信息
	*/
	public function do_delete() {
        global $_G;
        $tc_id = isset($_REQUEST['tc_id']) ? $_REQUEST['tc_id'] : '';
        if($tc_id){
            $effect_row = $this->delete("trade_course", array("tc_id" => $tc_id), $limit=1);
            if($effect_row){
                showmessage('操作成功','index.php?mod=trade&action=course&do=index');
            }else{
                showmessage('操作失败','index.php?mod=trade&action=course&do=index');
            }
        }
    }
	
    /*
     *  系统信息列表
     */
    public function do_index(){
    	global $_G;
    	//ini_set("display_errors","On");
    	//error_reporting(E_ALL);
    	$default_limit=20;
    	$page = max(1, intval($_GET['page']));
    	$perpage = $limit = isset($_REQUEST['limit']) && !empty($_REQUEST['limit']) ? $_REQUEST['limit'] : $default_limit;
    	$start=(($page-1) * $perpage);    	    	   	    	    	
    	$wheresql = " AND tc_flag=2 AND isdelete = 0 ";    		
    	if(!$_G['user_id']){
    		$noauth = [
    				'code'=>'10000',
    				'msg'=>lang('core','noauth'),
    				'data'=>[]
    		];
    		echo json_encode($noauth,JSON_FORCE_OBJECT);return false;
    
    	}
    	$user_id = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : '';
    	if(!$user_id){
    		$return['code'] = '1';
    		$return['data']=[];
    		echo format_data($return,$_G['gp_api'],$_G['gp_mod'],$_G['gp_action'],$_G['gp_do']);
    		return false;
    	}
    	if($_G['member']['role_id']==3){  //后台总管理员权限
    		$so_id = isset($_REQUEST['so_id']) ? $_REQUEST['so_id'] : '0';    		
    		$wheresql .= " AND user_id=".$user_id;    		   		
    	}else{  
    		//查询是否是网校的学员
    		$so_id = $this->one_so_info('user_detail', 'user_id', $user_id);
    		if($so_id!=$_REQUEST['so_id']){
    			$return['code'] = '2';
    			$return['data']=[];
    			echo format_data($return,$_G['gp_api'],$_G['gp_mod'],$_G['gp_action'],$_G['gp_do']);
    			return false;
    		}else{
    			$wheresql .= " AND user_id=".$user_id;
    		}
    		
    	}    	
    	$orderby = " ORDER BY tc_id DESC ";
    	//DEBUG 初始化请求请求获取一页列表数据的参数
    	$page_condition=array(
    			'page' => $page,//int 请求页面 页码
    			'limit' => $limit,//int 每页请求个数
    			'perpage' => $perpage,//int 每页显示个数
    			'wheresql' => $wheresql,//string //条件SQL语句
    			'orderby' => $orderby,//string 排序规则
    	);
    	//DEBUG 列表数据返回结构
    	/*
    	 $page_result = array(
    	 //int 返回结果总数
    	 'total_rows' => $total_rows,
    	 //array 一页数据数组
    	 'page_data' => $page_data
    	 );
    	*/
    	$page_result = $this->course_index('trade_course',$page_condition);
    	foreach($page_result['page_data'] AS $key => $value){
    		$page_result['page_data'][$key]=$value['cm_id'];
    		$page_result['page_data_tmp'][$value['cm_id']]['nowClass']=$value['nowClass'];
    		$page_result['page_data_tmp'][$value['cm_id']]['classTime']=$value['classTime'];
    	}
    	$course_res = self::get_course_field_value_by_id('course_main','cm_id',$page_result['page_data'],'cm_cate_id,cm_start_time,cm_brief,cm_id,cm_name,cm_brief,cm_img,cm_price,cm_count,so_id,so_id,cm_hour_num,create_dateline,is_group');
    	$page_result['page_now']=$page;
    	$page_result['total_page']=max(1, ceil(count($course_res)/$perpage));
    	//int 返回结果总数
    	$page_result['total_rows'] = count($course_res);
    	//组合课程和普通课程手动分页
    	$totalRows = count($sql_result);
    	$newRes = array_chunk($course_res , $limit);
    
    	$course_info = $newRes[$page - 1];
 
    	unset($page_result['page_data']);
    	$client = isset($_REQUEST['client']) ? $_REQUEST['client'] : 'pc';
    	if($course_info){
    		foreach($course_info AS $key=>$value){
    			$tmp=array();
    			$tmp['type'] = $value['cm_cate_id'];
    			$tmp['startTime'] = date('Y-m-d',$value['cm_start_time']);
    			$tmp['title'] = $value['cm_name'];
    			$tmp['price'] = $value['cm_price'];
    			$tmp['school'] = $this->get_course_field_value_by_id('school_online','so_id',$value['so_id'],'so_name');
    			$tmp['id'] = $value['cm_id'];
    			$tmp['img'] = $value['cm_img'];
    			$tmp['info'] = $value['cm_brief'];
    			$tmp['times'] = $value['cm_hour_num'];
    			$page_result['page_data'][]=$tmp;
    		}
    	}else{
    		$page_result['page_data']=[];
    	}
    	unset($page_result['page_data_tmp']);
    	//DEBUG 获取课程信息
    
    	if($page_result){
    		$return['code'] = '0';
    		$return['data'][$_G['gp_mod'].'_'.$_G['gp_action'].'_'.$_G['gp_do']]=$page_result;
    		if($client=='pc'){
    			$return['data']=$page_result;
    		}else{
    			$return['data'][$_G['gp_mod'].'_'.$_G['gp_action'].'_'.$_G['gp_do']]=$page_result;
    		}
    		
    	}else{
    		$return['code'] = '1';
    		$return['data']=[];
    	}
    	echo format_data($return,$_G['gp_api'],$_G['gp_mod'],$_G['gp_action'],$_G['gp_do']);
    }

    /**
    * 接口 AJAX或外部请求检索数据
    *
    * @param $return_type string json/xml.
    *
    * @return print string json/xml.
    */
    public function do_api(){
        $return = '';
        $page = max(1, intval($_GET['page']));
        $perpage = $limit = 20;
        $start=(($page-1) * $perpage);
        $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';
        $return_type = isset($_REQUEST['return_type']) ? $_REQUEST['return_type'] : 'json';
        $wheresql = "";
        if($keyword){
            $wheresql = " WHERE title LIKE '%".$keyword."%'";
        }
        $orderby = " ORDER BY tc_id DESC ";
        //DEBUG 初始化请求请求获取一页列表数据的参数
        $page_condition=array(
            'page' => $page,//int 请求页面 页码
            'limit' => $limit,//int 每页请求个数
            'perpage' => $perpage,//int 每页显示个数
            'wheresql' => $wheresql,//string //条件SQL语句 
            'orderby' => $orderby,//string 排序规则
        );
        //DEBUG 列表数据返回结构
        /*
        $page_result = array(
            //int 返回结果总数
            'total_rows' => $total_rows,
            //array 一页数据数组
            'page_data' => $page_data 
        );
        */
        $page_result = $this->api('trade_course',$page_condition);      
        if('json'==$return_type){
            $return = json_encode($page_result);	
        }elseif('xml'==$return_type){
            $return = array2xml($page_result);
        }
        //DEBUG 接口响应直接输出返回
        echo $return;
    }
    
    /*
     * 选课统计 结果集导出
     */
    public function do_export(){
        global $_G;
        
        //此处接收传递的搜索条件
        $cs_am_id_1 = isset($_REQUEST['am_id_1']) && !empty($_REQUEST['am_id_1']) ? $_REQUEST['am_id_1'] : '';//省
        $cs_am_id_2 = isset($_REQUEST['am_id_2']) && !empty($_REQUEST['am_id_2']) ? $_REQUEST['am_id_2'] : '';//市
        $cs_am_id_3 = isset($_REQUEST['am_id_3']) && !empty($_REQUEST['am_id_3']) ? $_REQUEST['am_id_3'] : '';//县
        $cs_sm_id = isset($_REQUEST['sm_id']) && !empty($_REQUEST['sm_id']) ? $_REQUEST['sm_id'] : '';//学校
        $cs_class_id = isset($_REQUEST['class_id']) && !empty($_REQUEST['class_id']) ? $_REQUEST['class_id'] : '';//班级
        $cs_cm_id = isset($_REQUEST['cm_id']) && !empty($_REQUEST['cm_id']) ? $_REQUEST['cm_id'] : '';//课程编号 必填项
        $cs_cm_cate_id = isset($_REQUEST['cm_cate_id']) && !empty($_REQUEST['cm_cate_id']) ? $_REQUEST['cm_cate_id'] : '';//课程分类
        $cs_cm_grade_id = isset($_REQUEST['cm_grade_id']) && !empty($_REQUEST['cm_grade_id']) ? $_REQUEST['cm_grade_id'] : '';//年级属性
        $cs_cm_subject_id = isset($_REQUEST['cm_subject_id']) && !empty($_REQUEST['cm_subject_id']) ? $_REQUEST['cm_subject_id'] : '';//学科属性
        
        //如果没有传递进来要查询的课程编号
        if(!$cs_cm_id){
            $return['code'] = '1';
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        
        $whereSql = " and cs_cm_id = '".$cs_cm_id."' ";
        
        $flag = 1;//1.查询全国所有的省份信息 2.查询指定省份的所有城市信息 3.查询指定市的所有县信息 4.查询指定县的所有学校信息 5.查询制定学校的所有班级信息 6.查询制定班级所有选课的学生
        //此处先划分一下本次查询的结果集范围
        //1.如果没有传递进来任何地区检索信息的话 则默认查询所有的省份
        //2.如果传递进来了省份的信息的话，默认查询所有市的信息
        //3.如果传递进来了市的信息的话，则查询对应县的信息
        //4.如果传递进来了县的信息的话，则查询对应学校的信息
        //5.如果传递进来了指定学校的信息的话，则查询对应班级的信息
        //6.如果传递进来了指定班级的信息的话，则查询对应那些学生选了该课程
        if($cs_am_id_1){//传递进来了 省份
            $whereSql.= " and cs_am_id_1 = ".$cs_am_id_1." ";
            $flag = 2;
        }
        
        if($cs_am_id_2){//传递进来了 市
            $whereSql.= " and cs_am_id_2 = ".$cs_am_id_2." ";
            $flag = 3;
        }
        
        if($cs_am_id_3){//传递进来了 县
            $whereSql.= " and cs_am_id_3 = ".$cs_am_id_3." ";
            $flag = 4;
        }
        
        if($cs_sm_id){//传递进来了 学校
            $whereSql.= " and cs_sm_id = ".$cs_sm_id." ";
            $flag = 5;
        }
        
        if($cs_class_id){//传递进来了 班级
            $whereSql.= " and cs_class_id = ".$cs_class_id." ";
            $flag = 6;
        }
        
        if($cs_cm_cate_id){//如果传递进来了课程分类
            $whereSql.= " and cs_cm_cate_id = '".$cs_cm_cate_id."' ";
        }
        
        if($cs_cm_grade_id){//如果传递进来了年级属性
            $whereSql.= " and cs_cm_grade_id = '".$cs_cm_grade_id."' ";
        }
        
        if($cs_cm_subject_id){//如果传递进来了学科属性
            $whereSql.= " and cs_cm_subject_id = '".$cs_cm_subject_id."' ";
        }
        
        $queries = '';
        $groupby = '';
        switch ($flag) {
            case 1://查全国所有省份
                $queries = " count(*) as cnt, cs_am_id_1 as k ";
                $groupby = " group by cs_am_id_1 ";
                break;
            case 2://查指定省份所有市
                $queries = " count(*) as cnt, cs_am_id_2 as k ";
                $groupby = " group by cs_am_id_2 ";
                break;
            case 3://查指定市所有县
                $queries = " count(*) as cnt, cs_am_id_3 as k ";
                $groupby = " group by cs_am_id_3 ";
                break;
            case 4://查指定县所有学校
                $queries = " count(*) as cnt, cs_sm_id as k ";
                $groupby = " group by cs_sm_id ";
                break;
            case 5://查指定学校所有班级
                $queries = " count(*) as cnt, cs_class_id as k ";
                $groupby = " group by cs_class_id ";
                break;
            case 6://查指定班级所有选课学生
                $queries = " count(*) as cnt, cs_user_id as k ";
                $groupby = " group by cs_user_id ";
                break;
            default:
                break;
        }
        
        $sql = "select ".$queries." from ".DB::table('course_statistics')." where 1 = 1 ".$whereSql.$groupby;
        
        $res = DB::fetch_all($sql);
        
        //列表中需显示对应的名称
        if(!empty($res) && is_array($res)){
            foreach ($res as $k => $item) {
                if(($flag == 1) || ($flag == 2) || ($flag == 3)){//查询地区名称
                    $sql = "select am_name from ".DB::table('area_main')." where am_id = '".$item['k']."' ";
                }
                elseif($flag == 4){//查学校名称
                    $sql = "select sm_name from ".DB::table('school_main')." where sm_id = '".$item['k']."' ";
                }
                elseif($flag == 5){//查班级名称
                    $sql = "select class_name from ".DB::table('class_main')." where class_id = '".$item['k']."' ";
                }
                elseif($flag == 6){//查学生名称
                    $sql = "select user_realname from ".DB::table('user_detail')." where user_id = '".$item['k']."' ";
                }
                
                $res[$k]['name'] = DB::result_first($sql);
            }
        }
        
        //开始组装目标数组
        $filename = 'xktj'.date('YmdHis').'.csv'; //设置文件名
        $f = ',';//定义分隔符
        $list[] = iconv("utf-8","gb2312",'名称'.$f.'数量');

        //将上述结果集转换为目标数组
        if(!empty($res) && is_array($res)){
            foreach ($res as $item) {
                $list[] = iconv("utf-8","gb2312",$item['name'].$f.$item['cnt']);
            }
        }
        
        $target = SITE_ROOT.'data/upload/';
        $fp = fopen($target.$filename, 'w');
        //向目标文件写入操作
        foreach ($list as $line) {
            fputcsv($fp, explode(',', $line));
        }

        fclose($fp);
        
        $return['code'] = '1';
        //检测是否对应已生成csv文件
        if(is_file($target.$filename)){
            //2017-6-6 11:51:34 此处将该csv文件上传到文件服务器，同时删除本地的文件
            $data = ['filedata'  =>  new CURLFile($target.$filename), 'dir' => '/'];
            $ch = curl_init();

            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            curl_setopt($ch, CURLOPT_URL, 'http://101.37.15.34/upload.php');
            curl_setopt($ch, CURLOPT_POST, true );
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $res = curl_exec($ch);
            curl_close($ch);

            //此处删除掉本地的文件
            @unlink($target.$filename);

            if($res == 'success'){//成功
               $return['code'] = '0';
               $return['data']['url'] = 'http://fstore.jxzhjy.com/data/upload/'.$filename;
            }
            else{//远程文件上传失败
               $return['code'] = '1';
               $return['data']= [];
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /**
    * 选课统计表数据修复脚本
    * php admin/cli.php -m trade -a course -d courserepair
    */
    public function do_courserepair(){
        @set_time_limit(0);
        
        global $_G;
        
        $isCli = is_cli();
        
        if(!$isCli){
            $return['code'] = '1';//非 cli 模式运行强制退出！
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        
        //课程表数据池
        $courseArr = [];
        //用户表数据池
        $userArr = [];
        //学校信息表数据池
        $schoolArr = [];
        //订单表数据池
        $tradeArr = [];
        
        // MARK: 2016-10-19 以订单课程表为此脚本主表进行扫描修复
        $start = 0;
        // 定义步长
        $stepSize = 5000;
        // 获取数据总数
        $sql_cnt = "select count(*) as cnt from ".DB::table('trade_course')." where isdelete = 0 and tc_flag = 2 and tc_type = 0 ";
        $count = DB::result_first($sql_cnt);
        
        while($count > 0){//如果还有尚未处理的数据
            // 按照步长吞入内存数据
            $resArr = [];//定义接收结果池
            
            $sql_res = "select tc_id, user_id, cm_id, group_cm_id, cm_price, tm_id, tc_applicant "
                    . " from ".DB::table('trade_course')." where isdelete = 0 and tc_flag = 2 and tc_type = 0 "
                    . " limit ".$start.", ".$stepSize;
            $resArr = DB::fetch_all($sql_res);
            
            if(!empty($resArr) && is_array($resArr)){
                foreach ($resArr as $item) {//遍历目标结果集重新组装数据
                    // 目标数据格式
                    // data['cs_cm_id'] //课程编号，关联pre_course_main.cm_id *
                    // data['cs_user_id'] //用户编号，关联pre_user.user_id * 
                    // data['cs_sm_id'] //学校编号，关联pre_school_main.sm_id *
                    // data['cs_sm_type'] //学校类别，关联pre_school_main.sm_type，1：小学，2：初中，3：高中，4：一贯制 *
                    // data['cs_class_id'] //班级编号，关联pre_class_main.class_id *
                    // data['cs_am_id_1'] //地区编号，关联pre_area_main.am_id 省 *
                    // data['cs_am_id_2'] //地区编号，关联pre_area_main.am_id 市 *
                    // data['cs_am_id_3'] //地区编号，关联pre_area_main.am_id 县 *
                    // data['cs_so_id'] //网校编号，关联pre_course_main.so_id *
                    // data['cs_cm_price'] //收费额度，关联pre_course_main.cm_price *
                    // data['cs_cm_cate_id'] //课程分类，关联pre_course_main.cm_cate_id *
                    // data['cs_cm_grade_id'] //年级属性，关联pre_course_main.cm_grade_id *
                    // data['cs_cm_subject_id'] //学科属性，关联pre_course_main.cm_subject_id *
                    // data['cs_cm_cc_id_1_1'] //课程系统一级分类，关联pre_course_main *
                    // data['cs_cm_cc_id_1_2'] //课程系统二级分类，关联pre_course_main *
                    // data['cs_cm_cc_id_1_3'] //课程系统三级分类，关联pre_course_main *
                    // data['cs_cm_cc_id_2_1'] //网校自建一级分类，关联pre_course_main *
                    // data['cs_cm_cc_id_2_2'] //网校自建二级分类，关联pre_course_main *
                    // data['cs_cm_cc_id_2_3'] //网校自建三级分类，关联pre_course_main *
                    // data['cs_cm_cc_id_3_1'] //自定义自建一级分类，关联pre_course_main *
                    // data['cs_cm_cc_id_3_2'] //自定义自建二级分类，关联pre_course_main *
                    // data['cs_cm_cc_id_3_3'] //自定义自建三级分类，关联pre_course_main *
                    // data['cs_tc_id'] //订单选课表主键，关联pre_trade_course.tc_id *
                    // data['cs_group_cm_id'] //组合课程编号，关联pre_trade_course.group_cm_id *
                    // data['cs_tm_id'] //订单表主键，关联pre_trade_course.tm_id *
                    // data['cs_tc_applicant'] //选课申请人编号 0 表示选课人自己申请 关联pre_trade_course *
                    // data['cs_tm_out_trade_no'] //网校订单号，关联pre_trade_main
                    // data['cs_tm_trade_no'] //支付交易号
                    // data['cs_tm_way'] //1 支付宝 2 人工收款 3 支付宝网银支付
                    // data['cs_tm_bank_code'] //网银支付的银行简码
                    // data['cs_is_free'] //是否免费订单：1.免费 0.非免费
                    $data = [];
                    //直接可获取部分
                    $data['cs_cm_id'] = $item['cm_id'];
                    $data['cs_tc_id'] = $item['tc_id'];
                    $data['cs_user_id'] = $item['user_id'];
                    $data['cs_group_cm_id'] = $item['group_cm_id'];
                    $data['cs_cm_price'] = $item['cm_price'];
                    $data['cs_tm_id'] = $item['tm_id'];
                    $data['cs_tc_applicant'] = $item['tc_applicant'];
                    //从课程表中查询出来的数据
                    if(isset($courseArr[$item['cm_id']])){//如果查询结果池中存在该数据则直接获取
                        $data['cs_so_id'] = $courseArr[$item['cm_id']]['so_id'];
                        $data['cs_cm_price'] = $courseArr[$item['cm_id']]['cm_price'];
                        $data['cs_cm_cate_id'] = $courseArr[$item['cm_id']]['cm_cate_id'];
                        $data['cs_cm_grade_id'] = $courseArr[$item['cm_id']]['cm_grade_id'];
                        $data['cs_cm_subject_id'] = $courseArr[$item['cm_id']]['cm_subject_id'];
                        $data['cs_cm_cc_id_1_1'] = $courseArr[$item['cm_id']]['cm_cc_id_1_1'];
                        $data['cs_cm_cc_id_1_2'] = $courseArr[$item['cm_id']]['cm_cc_id_1_2'];
                        $data['cs_cm_cc_id_1_3'] = $courseArr[$item['cm_id']]['cm_cc_id_1_3'];
                        $data['cs_cm_cc_id_2_1'] = $courseArr[$item['cm_id']]['cm_cc_id_2_1'];
                        $data['cs_cm_cc_id_2_2'] = $courseArr[$item['cm_id']]['cm_cc_id_2_2'];
                        $data['cs_cm_cc_id_2_3'] = $courseArr[$item['cm_id']]['cm_cc_id_2_3'];
                        $data['cs_cm_cc_id_3_1'] = $courseArr[$item['cm_id']]['cm_cc_id_3_1'];
                        $data['cs_cm_cc_id_3_2'] = $courseArr[$item['cm_id']]['cm_cc_id_3_2'];
                        $data['cs_cm_cc_id_3_3'] = $courseArr[$item['cm_id']]['cm_cc_id_3_3'];
                    }
                    else{//查询对应数据库并将结果集存放到结果池中去
                        $sql_course_res = "select so_id, cm_price, cm_cate_id, cm_grade_id, cm_subject_id, cm_cc_id_1_1, cm_cc_id_1_2, cm_cc_id_1_3, cm_cc_id_2_1, cm_cc_id_2_2, cm_cc_id_2_3, cm_cc_id_3_1, cm_cc_id_3_2, cm_cc_id_3_3 "
                                . " from ".DB::table('course_main')." where cm_id = '".$item['cm_id']."'";
                        $courseResArr = DB::fetch_first($sql_course_res);
                        
                        $data['cs_so_id'] = $courseResArr['so_id'];
                        $data['cs_cm_price'] = $courseResArr['cm_price'];
                        $data['cs_cm_cate_id'] = $courseResArr['cm_cate_id'];
                        $data['cs_cm_grade_id'] = $courseResArr['cm_grade_id'];
                        $data['cs_cm_subject_id'] = $courseResArr['cm_subject_id'];
                        $data['cs_cm_cc_id_1_1'] = $courseResArr['cm_cc_id_1_1'];
                        $data['cs_cm_cc_id_1_2'] = $courseResArr['cm_cc_id_1_2'];
                        $data['cs_cm_cc_id_1_3'] = $courseResArr['cm_cc_id_1_3'];
                        $data['cs_cm_cc_id_2_1'] = $courseResArr['cm_cc_id_2_1'];
                        $data['cs_cm_cc_id_2_2'] = $courseResArr['cm_cc_id_2_2'];
                        $data['cs_cm_cc_id_2_3'] = $courseResArr['cm_cc_id_2_3'];
                        $data['cs_cm_cc_id_3_1'] = $courseResArr['cm_cc_id_3_1'];
                        $data['cs_cm_cc_id_3_2'] = $courseResArr['cm_cc_id_3_2'];
                        $data['cs_cm_cc_id_3_3'] = $courseResArr['cm_cc_id_3_3'];
                     
                        $courseArr[$item['cm_id']] = $courseResArr;
                    }
                    
                    //从用户详情表中获取对应信息
                    if(isset($userArr[$item['user_id']])){//如果查询结果池中存在该数据则直接获取
                        $data['cs_am_id_1'] = $userArr[$item['user_id']]['am_id_1'];
                        $data['cs_am_id_2'] = $userArr[$item['user_id']]['am_id_2'];
                        $data['cs_am_id_3'] = $userArr[$item['user_id']]['am_id_3'];
                        $data['cs_sm_id'] = $userArr[$item['user_id']]['sm_id'];
                        $data['cs_class_id'] = $userArr[$item['user_id']]['class_id'];
                    }
                    else{//查询对应数据库并将结果集存放到结果池中去
                        $sql_user_res = "select am_id_1, am_id_2, am_id_3, sm_id, class_id "
                                . " from ".DB::table('user_detail')." where user_id = '".$item['user_id']."'";
                        $userResArr = DB::fetch_first($sql_user_res);
                        
                        $data['cs_am_id_1'] = $userResArr['am_id_1'];
                        $data['cs_am_id_2'] = $userResArr['am_id_2'];
                        $data['cs_am_id_3'] = $userResArr['am_id_3'];
                        $data['cs_sm_id'] = $userResArr['sm_id'];
                        $data['cs_class_id'] = $userResArr['class_id'];
                     
                        $userArr[$item['user_id']] = $userResArr;
                    }
                    
                    //从学校表中获取对应信息
                    if(isset($schoolArr[$data['cs_sm_id']])){//如果查询结果池中存在该数据则直接获取
                        $data['cs_sm_type'] = $schoolArr[$data['cs_sm_id']]['sm_type'];
                    }
                    else{//查询对应数据库并将结果集存放到结果池中去
                        $sql_school_res = "select sm_type "
                                . " from ".DB::table('school_main')." where sm_id = '".$data['cs_sm_id']."'";
                        $schoolResArr = DB::fetch_first($sql_school_res);
                        
                        $data['cs_sm_type'] = $schoolResArr['sm_type'];
                     
                        $schoolArr[$data['cs_sm_id']] = $schoolResArr;
                    }
                    
                    //从订单表中获取对应信息
                    if(isset($tradeArr[$item['tm_id']])){//如果查询结果池中存在该数据则直接获取
                        $data['cs_tm_out_trade_no'] = $tradeArr[$item['tm_id']]['tm_out_trade_no'];
                        $data['cs_tm_trade_no'] = $tradeArr[$item['tm_id']]['tm_trade_no'];
                        $data['cs_tm_way'] = $tradeArr[$item['tm_id']]['tm_way'];
                        $data['cs_tm_bank_code'] = $tradeArr[$item['tm_id']]['tm_bank_code'];
                        $data['cs_is_free'] = $tradeArr[$item['tm_id']]['is_free'];
                    }
                    else{//查询对应数据库并将结果集存放到结果池中去
                        $sql_trade_res = "select tm_out_trade_no, tm_trade_no, tm_way, tm_bank_code, is_free "
                                . " from ".DB::table('trade_main')." where tm_id = '".$item['tm_id']."'";
                        $tradeResArr = DB::fetch_first($sql_trade_res);
                        
                        $data['cs_tm_out_trade_no'] = $tradeResArr['tm_out_trade_no'];
                        $data['cs_tm_trade_no'] = $tradeResArr['tm_trade_no'];
                        $data['cs_tm_way'] = $tradeResArr['tm_way'];
                        $data['cs_tm_bank_code'] = $tradeResArr['tm_bank_code'];
                        $data['cs_is_free'] = $tradeResArr['is_free'];
                     
                        $tradeArr[$item['tm_id']] = $tradeResArr;
                    }
                    
                    // data 数据入库
                    $data['ctime'] = $data['mtime'] = TIMESTAMP;
                    
                    $this->add('course_statistics', $data);
                }
            }
            
            $start += $stepSize;//数据查询偏移量为步长
            $count -= $stepSize;//待处理数据量减少为步长
            
            sleep(1);//程序休息1秒
        }
        
        echo '程序执行完毕！\n';
        return false;
    }
    
    /**
    * 选课统计 省 市 县 学校 班级
    */
    public function do_coursestatistics(){
        global $_G;
        
        //此处接收传递的搜索条件
        $cs_am_id_1 = isset($_REQUEST['am_id_1']) && !empty($_REQUEST['am_id_1']) ? $_REQUEST['am_id_1'] : '';//省
        $cs_am_id_2 = isset($_REQUEST['am_id_2']) && !empty($_REQUEST['am_id_2']) ? $_REQUEST['am_id_2'] : '';//市
        $cs_am_id_3 = isset($_REQUEST['am_id_3']) && !empty($_REQUEST['am_id_3']) ? $_REQUEST['am_id_3'] : '';//县
        $cs_sm_id = isset($_REQUEST['sm_id']) && !empty($_REQUEST['sm_id']) ? $_REQUEST['sm_id'] : '';//学校
        $cs_class_id = isset($_REQUEST['class_id']) && !empty($_REQUEST['class_id']) ? $_REQUEST['class_id'] : '';//班级
        $cs_cm_id = isset($_REQUEST['cm_id']) && !empty($_REQUEST['cm_id']) ? $_REQUEST['cm_id'] : '';//课程编号 必填项
        $cs_cm_cate_id = isset($_REQUEST['cm_cate_id']) && !empty($_REQUEST['cm_cate_id']) ? $_REQUEST['cm_cate_id'] : '';//课程分类
        $cs_cm_grade_id = isset($_REQUEST['cm_grade_id']) && !empty($_REQUEST['cm_grade_id']) ? $_REQUEST['cm_grade_id'] : '';//年级属性
        $cs_cm_subject_id = isset($_REQUEST['cm_subject_id']) && !empty($_REQUEST['cm_subject_id']) ? $_REQUEST['cm_subject_id'] : '';//学科属性
        
        $page = isset($_REQUEST['page']) && !empty($_REQUEST['page']) ? $_REQUEST['page'] : 1;
        $limit = isset($_REQUEST['limit']) && !empty($_REQUEST['limit']) ? $_REQUEST['limit'] : 15;
        
        //如果没有传递进来要查询的课程编号
        if(!$cs_cm_id){
            $return['code'] = '1';
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        
        //此处获取当前要被查询的课程名称
        $cm_name = ext::get_cm_info($cs_cm_id, 'cm_name');
        $am_1_name = $am_2_name = $am_3_name = $sm_name = $class_name = '';//初始化信息项 省名称 市名称 县名称 学校名称 班级名称
        
        if($cs_am_id_1){//如果传递进来了 省份id 对应查询名称
            $info = $this->one_info('area_main', 'am_id', $cs_am_id_1);
            $am_1_name = $info['am_name'];
        }
        
        if($cs_am_id_2){//如果传递进来了 市区id 对应查询名称
            $info = $this->one_info('area_main', 'am_id', $cs_am_id_2);
            $am_2_name = $info['am_name'];
        }
        
        if($cs_am_id_3){//如果传递进来了 县区id 对应查询名称
            $info = $this->one_info('area_main', 'am_id', $cs_am_id_3);
            $am_3_name = $info['am_name'];
        }
        
        if($cs_sm_id){//如果传递进来了 学校id 对应查询名称
            $info = $this->one_info('school_main', 'sm_id', $cs_sm_id);
            $sm_name = $info['sm_name'];
        }
        
        if($cs_class_id){//如果传递进来了 班级id 对应查询名称
            $info = $this->one_info('class_main', 'class_id', $cs_class_id);
            $class_name = $info['class_name'];
        }
        
        $whereSql = " and cs_cm_id = '".$cs_cm_id."' ";
        
        $flag = 1;//1.查询全国所有的省份信息 2.查询指定省份的所有城市信息 3.查询指定市的所有县信息 4.查询指定县的所有学校信息 5.查询制定学校的所有班级信息 6.查询制定班级所有选课的学生
        //此处先划分一下本次查询的结果集范围
        //1.如果没有传递进来任何地区检索信息的话 则默认查询所有的省份
        //2.如果传递进来了省份的信息的话，默认查询所有市的信息
        //3.如果传递进来了市的信息的话，则查询对应县的信息
        //4.如果传递进来了县的信息的话，则查询对应学校的信息
        //5.如果传递进来了指定学校的信息的话，则查询对应班级的信息
        //6.如果传递进来了指定班级的信息的话，则查询对应那些学生选了该课程
        if($cs_am_id_1){//传递进来了 省份
            $whereSql.= " and cs_am_id_1 = ".$cs_am_id_1." ";
            $flag = 2;
        }
        
        if($cs_am_id_2){//传递进来了 市
            $whereSql.= " and cs_am_id_2 = ".$cs_am_id_2." ";
            $flag = 3;
        }
        
        if($cs_am_id_3){//传递进来了 县
            $whereSql.= " and cs_am_id_3 = ".$cs_am_id_3." ";
            $flag = 4;
        }
        
        if($cs_sm_id){//传递进来了 学校
            $whereSql.= " and cs_sm_id = ".$cs_sm_id." ";
            $flag = 5;
        }
        
        if($cs_class_id){//传递进来了 班级
            $whereSql.= " and cs_class_id = ".$cs_class_id." ";
            $flag = 6;
        }
        
        if($cs_cm_cate_id){//如果传递进来了课程分类
            $whereSql.= " and cs_cm_cate_id = '".$cs_cm_cate_id."' ";
        }
        
        if($cs_cm_grade_id){//如果传递进来了年级属性
            $whereSql.= " and cs_cm_grade_id = '".$cs_cm_grade_id."' ";
        }
        
        if($cs_cm_subject_id){//如果传递进来了学科属性
            $whereSql.= " and cs_cm_subject_id = '".$cs_cm_subject_id."' ";
        }
        
        $queries = '';
        $groupby = '';
        switch ($flag) {
            case 1://查全国所有省份
                $queries = " count(*) as cnt, cs_am_id_1 as k ";
                $groupby = " group by cs_am_id_1 ";
                break;
            case 2://查指定省份所有市
                $queries = " count(*) as cnt, cs_am_id_2 as k ";
                $groupby = " group by cs_am_id_2 ";
                break;
            case 3://查指定市所有县
                $queries = " count(*) as cnt, cs_am_id_3 as k ";
                $groupby = " group by cs_am_id_3 ";
                break;
            case 4://查指定县所有学校
                $queries = " count(*) as cnt, cs_sm_id as k ";
                $groupby = " group by cs_sm_id ";
                break;
            case 5://查指定学校所有班级
                $queries = " count(*) as cnt, cs_class_id as k ";
                $groupby = " group by cs_class_id ";
                break;
            case 6://查指定班级所有选课学生
                $queries = " count(*) as cnt, cs_user_id as k ";
                $groupby = " group by cs_user_id ";
                break;
            default:
                break;
        }
        
        $sql = "select ".$queries." from ".DB::table('course_statistics')." where 1 = 1 ".$whereSql.$groupby;
        $sql_result = DB::fetch_all($sql);
        
        $totalRows = count($sql_result);
        $newRes = array_chunk($sql_result, $limit);
        
        $res = $newRes[$page - 1];
        //列表中需显示对应的名称
        if(!empty($res) && is_array($res)){
            foreach ($res as $k => $item) {
                if(($flag == 1) || ($flag == 2) || ($flag == 3)){//查询地区名称
                    $sql = "select am_name from ".DB::table('area_main')." where am_id = '".$item['k']."' ";
                }
                elseif($flag == 4){//查学校名称
                    $sql = "select sm_name from ".DB::table('school_main')." where sm_id = '".$item['k']."' ";
                }
                elseif($flag == 5){//查班级名称
                    $sql = "select class_name from ".DB::table('class_main')." where class_id = '".$item['k']."' ";
                }
                elseif($flag == 6){//查学生名称
                    $sql = "select user_realname from ".DB::table('user_detail')." where user_id = '".$item['k']."' ";
                }
                
                $res[$k]['name'] = DB::result_first($sql);
                
                $res[$k]['cm_name'] = $cm_name;//课程名称
                
                $res[$k]['am_1_name'] = $am_1_name;//省名称 
                $res[$k]['am_2_name'] = $am_2_name;//市名称 
                $res[$k]['am_3_name'] = $am_3_name;//县名称 
                $res[$k]['sm_name'] = $sm_name;//学校名称 
                $res[$k]['class_name'] = $class_name;//班级名称
            }
        }
        
        //DEBUG 列表数据返回结构
        $page_result = array(
            'page_now' => $page,
            'total_page' => max(1, ceil($totalRows / $limit)),
            //int 返回结果总数
            'total_rows' => $totalRows,
            //array 一页数据数组
            'page_data' => $res
        );
        
        $return['code'] = '0';
        $return['data'] = $page_result;
        $return['data']['page_now'] = $page;
        $return['data']['total_page'] = ceil($return['data']['page_now'] / $limit);
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /**
    * 选课统计 详情图 省 市 县 学校 班级
    */
    public function do_coursedetails(){
        global $_G;
        
        //此处接收传递的搜索条件
        $cs_am_id_1 = isset($_REQUEST['am_id_1']) && !empty($_REQUEST['am_id_1']) ? $_REQUEST['am_id_1'] : '';//省
        $cs_am_id_2 = isset($_REQUEST['am_id_2']) && !empty($_REQUEST['am_id_2']) ? $_REQUEST['am_id_2'] : '';//市
        $cs_am_id_3 = isset($_REQUEST['am_id_3']) && !empty($_REQUEST['am_id_3']) ? $_REQUEST['am_id_3'] : '';//县
        $cs_sm_id = isset($_REQUEST['sm_id']) && !empty($_REQUEST['sm_id']) ? $_REQUEST['sm_id'] : '';//学校
        $cs_class_id = isset($_REQUEST['class_id']) && !empty($_REQUEST['class_id']) ? $_REQUEST['class_id'] : '';//班级
        $cs_cm_id = isset($_REQUEST['cm_id']) && !empty($_REQUEST['cm_id']) ? $_REQUEST['cm_id'] : '';//课程编号 必填项
        $cs_cm_cate_id = isset($_REQUEST['cm_cate_id']) && !empty($_REQUEST['cm_cate_id']) ? $_REQUEST['cm_cate_id'] : '';//课程分类
        $cs_cm_grade_id = isset($_REQUEST['cm_grade_id']) && !empty($_REQUEST['cm_grade_id']) ? $_REQUEST['cm_grade_id'] : '';//年级属性
        $cs_cm_subject_id = isset($_REQUEST['cm_subject_id']) && !empty($_REQUEST['cm_subject_id']) ? $_REQUEST['cm_subject_id'] : '';//学科属性
        
        //如果没有传递进来要查询的课程编号
        if(!$cs_cm_id){
            $return['code'] = '1';
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        
        //此处获取当前要被查询的课程名称
        $am_1_name = $am_2_name = $am_3_name = $sm_name = $class_name = '';//初始化信息项 省名称 市名称 县名称 学校名称 班级名称
        
        if($cs_am_id_1){//如果传递进来了 省份id 对应查询名称
            $info = $this->one_info('area_main', 'am_id', $cs_am_id_1);
            $am_1_name = $info['am_name'];
        }
        
        if($cs_am_id_2){//如果传递进来了 市区id 对应查询名称
            $info = $this->one_info('area_main', 'am_id', $cs_am_id_2);
            $am_2_name = $info['am_name'];
        }
        
        if($cs_am_id_3){//如果传递进来了 县区id 对应查询名称
            $info = $this->one_info('area_main', 'am_id', $cs_am_id_3);
            $am_3_name = $info['am_name'];
        }
        
        if($cs_sm_id){//如果传递进来了 学校id 对应查询名称
            $info = $this->one_info('school_main', 'sm_id', $cs_sm_id);
            $sm_name = $info['sm_name'];
        }
        
        if($cs_class_id){//如果传递进来了 班级id 对应查询名称
            $info = $this->one_info('class_main', 'class_id', $cs_class_id);
            $class_name = $info['class_name'];
        }
        
        $whereSql = " and cs_cm_id = '".$cs_cm_id."' ";
        
        $flag = 1;//1.查询全国所有的省份信息 2.查询指定省份的所有城市信息 3.查询指定市的所有县信息 4.查询指定县的所有学校信息 5.查询制定学校的所有班级信息 6.查询制定班级所有选课的学生
        //此处先划分一下本次查询的结果集范围
        //1.如果没有传递进来任何地区检索信息的话 则默认查询所有的省份
        //2.如果传递进来了省份的信息的话，默认查询所有市的信息
        //3.如果传递进来了市的信息的话，则查询对应县的信息
        //4.如果传递进来了县的信息的话，则查询对应学校的信息
        //5.如果传递进来了指定学校的信息的话，则查询对应班级的信息
        //6.如果传递进来了指定班级的信息的话，则查询对应那些学生选了该课程
        if($cs_am_id_1){//传递进来了 省份
            $whereSql.= " and cs_am_id_1 = ".$cs_am_id_1." ";
            $flag = 2;
        }
        
        if($cs_am_id_2){//传递进来了 市
            $whereSql.= " and cs_am_id_2 = ".$cs_am_id_2." ";
            $flag = 3;
        }
        
        if($cs_am_id_3){//传递进来了 县
            $whereSql.= " and cs_am_id_3 = ".$cs_am_id_3." ";
            $flag = 4;
        }
        
        if($cs_sm_id){//传递进来了 学校
            $whereSql.= " and cs_sm_id = ".$cs_sm_id." ";
            $flag = 5;
        }
        
        if($cs_class_id){//传递进来了 班级
            $whereSql.= " and cs_class_id = ".$cs_class_id." ";
            $flag = 6;
        }
        
        if($cs_cm_cate_id){//如果传递进来了课程分类
            $whereSql.= " and cs_cm_cate_id = '".$cs_cm_cate_id."' ";
        }
        
        if($cs_cm_grade_id){//如果传递进来了年级属性
            $whereSql.= " and cs_cm_grade_id = '".$cs_cm_grade_id."' ";
        }
        
        if($cs_cm_subject_id){//如果传递进来了学科属性
            $whereSql.= " and cs_cm_subject_id = '".$cs_cm_subject_id."' ";
        }
        
        $queries = '';
        $groupby = '';
        switch ($flag) {
            case 1://查全国所有省份
                $queries = " count(*) as cnt, cs_am_id_1 as k ";
                $groupby = " group by cs_am_id_1 ";
                break;
            case 2://查指定省份所有市
                $queries = " count(*) as cnt, cs_am_id_2 as k ";
                $groupby = " group by cs_am_id_2 ";
                break;
            case 3://查指定市所有县
                $queries = " count(*) as cnt, cs_am_id_3 as k ";
                $groupby = " group by cs_am_id_3 ";
                break;
            case 4://查指定县所有学校
                $queries = " count(*) as cnt, cs_sm_id as k ";
                $groupby = " group by cs_sm_id ";
                break;
            case 5://查指定学校所有班级
                $queries = " count(*) as cnt, cs_class_id as k ";
                $groupby = " group by cs_class_id ";
                break;
            case 6://查指定班级所有选课学生
                $queries = " count(*) as cnt, cs_user_id as k ";
                $groupby = " group by cs_user_id ";
                break;
            default:
                break;
        }
        
        $sql = "select ".$queries." from ".DB::table('course_statistics')." where 1 = 1 ".$whereSql.$groupby;
        $res = DB::fetch_all($sql);
        
        //列表中需显示对应的名称
        if(!empty($res) && is_array($res)){
            foreach ($res as $k => $item) {
                if(($flag == 1) || ($flag == 2) || ($flag == 3)){//查询地区名称
                    $sql = "select am_name from ".DB::table('area_main')." where am_id = '".$item['k']."' ";
                }
                elseif($flag == 4){//查学校名称
                    $sql = "select sm_name from ".DB::table('school_main')." where sm_id = '".$item['k']."' ";
                }
                elseif($flag == 5){//查班级名称
                    $sql = "select class_name from ".DB::table('class_main')." where class_id = '".$item['k']."' ";
                }
                elseif($flag == 6){//查学生名称
                    $sql = "select user_realname from ".DB::table('user_detail')." where user_id = '".$item['k']."' ";
                }
                
                $res[$k]['name'] = DB::result_first($sql);
            }
        }
        
        //将结果集拆分为 key 和 value 两个不同的数组
        $keyArr = [];
        $valArr = [];
        
        if(!empty($res) && is_array($res)){
            foreach ($res as $k => $item) {
                $keyArr[] = $item['name'];
                $valArr[] = $item['cnt'];
            }
        }
        
        $return['code'] = '0';
        $return['data'] = ['key' => $keyArr, 'val' => $valArr];
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     * 选课统计 结果集导出
     */
    public function do_courseexport(){
        global $_G;
        
        //此处接收传递的搜索条件
        $cs_am_id_1 = isset($_REQUEST['am_id_1']) && !empty($_REQUEST['am_id_1']) ? $_REQUEST['am_id_1'] : '';//省
        $cs_am_id_2 = isset($_REQUEST['am_id_2']) && !empty($_REQUEST['am_id_2']) ? $_REQUEST['am_id_2'] : '';//市
        $cs_am_id_3 = isset($_REQUEST['am_id_3']) && !empty($_REQUEST['am_id_3']) ? $_REQUEST['am_id_3'] : '';//县
        $cs_sm_id = isset($_REQUEST['sm_id']) && !empty($_REQUEST['sm_id']) ? $_REQUEST['sm_id'] : '';//学校
        $cs_class_id = isset($_REQUEST['class_id']) && !empty($_REQUEST['class_id']) ? $_REQUEST['class_id'] : '';//班级
        $cs_cm_id = isset($_REQUEST['cm_id']) && !empty($_REQUEST['cm_id']) ? $_REQUEST['cm_id'] : '';//课程编号 必填项
        $cs_cm_cate_id = isset($_REQUEST['cm_cate_id']) && !empty($_REQUEST['cm_cate_id']) ? $_REQUEST['cm_cate_id'] : '';//课程分类
        $cs_cm_grade_id = isset($_REQUEST['cm_grade_id']) && !empty($_REQUEST['cm_grade_id']) ? $_REQUEST['cm_grade_id'] : '';//年级属性
        $cs_cm_subject_id = isset($_REQUEST['cm_subject_id']) && !empty($_REQUEST['cm_subject_id']) ? $_REQUEST['cm_subject_id'] : '';//学科属性
        
        $cs_type = isset($_REQUEST['type']) && !empty($_REQUEST['type']) ? $_REQUEST['type'] : 0;//统计时间范围
        
        //如果没有传递进来要查询的课程编号
        if(!$cs_cm_id){
            $return['code'] = '1';
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        
        $stime = 0;
        
        if($cs_type == 1){//近7天
            $stime = TIMESTAMP - 7 * 86400;
        }
        elseif($cs_type == 2){//近三个月
            $stime = TIMESTAMP - 90 * 86400;
        }
        elseif($cs_type == 3){//近一年
            $stime = TIMESTAMP - 365 * 86400;
        }
        
        $whereSql = " and cs_cm_id = '".$cs_cm_id."' and ctime >= '".$stime."' ";
        
        if($cs_am_id_1){//传递进来了 省份
            $whereSql.= " and cs_am_id_1 = ".$cs_am_id_1." ";
        }
        
        if($cs_am_id_2){//传递进来了 市
            $whereSql.= " and cs_am_id_2 = ".$cs_am_id_2." ";
        }
        
        if($cs_am_id_3){//传递进来了 县
            $whereSql.= " and cs_am_id_3 = ".$cs_am_id_3." ";
        }
        
        if($cs_sm_id){//传递进来了 学校
            $whereSql.= " and cs_sm_id = ".$cs_sm_id." ";
        }
        
        if($cs_class_id){//传递进来了 班级
            $whereSql.= " and cs_class_id = ".$cs_class_id." ";
        }
        
        if($cs_cm_cate_id){//如果传递进来了课程分类
            $whereSql.= " and cs_cm_cate_id = '".$cs_cm_cate_id."' ";
        }
        
        if($cs_cm_grade_id){//如果传递进来了年级属性
            $whereSql.= " and cs_cm_grade_id = '".$cs_cm_grade_id."' ";
        }
        
        if($cs_cm_subject_id){//如果传递进来了学科属性
            $whereSql.= " and cs_cm_subject_id = '".$cs_cm_subject_id."' ";
        }
        
        $queries = " count(*) as cnt, cs_user_id as k ";
        $groupby = " group by cs_user_id ";
        
        $sql = "select ".$queries." from ".DB::table('course_statistics')." where 1 = 1 ".$whereSql.$groupby;
        
        $res = DB::fetch_all($sql);
        
        //列表中需显示对应的名称
        if(!empty($res) && is_array($res)){
            //地区信息表数据池
            $amArr = [];
            //学校信息表数据池
            $schoolArr = [];
            //班级信息表数据池
            $classArr = [];
            
            foreach ($res as $k => $item) {
                $sql = "select am_id_1, am_id_2, am_id_3, sm_id, class_id, user_realname from ".DB::table('user_detail')." where user_id = '".$item['k']."' ";
                $tmpData = DB::fetch_first($sql);
                
                //此处需要获取用户的区限信息  学校名称  班级名称
                $res[$k]['name'] = $tmpData['user_realname'];
                
                if(isset($amArr[$tmpData['am_id_1']])){
                    $res[$k]['am_1'] = $amArr[$tmpData['am_id_1']];
                }
                else{
                    $sql = "select am_name from ".DB::table('area_main')." where am_id = '".$tmpData['am_id_1']."' ";
                    $tmAm_1 = DB::result_first($sql);
                    
                    $amArr[$tmpData['am_id_1']] = $tmAm_1;
                    $res[$k]['am_1'] = $tmAm_1;
                }
                
                if(isset($amArr[$tmpData['am_id_2']])){
                    $res[$k]['am_2'] = $amArr[$tmpData['am_id_2']];
                }
                else{
                    $sql = "select am_name from ".DB::table('area_main')." where am_id = '".$tmpData['am_id_2']."' ";
                    $tmAm_2 = DB::result_first($sql);
                    
                    $amArr[$tmpData['am_id_2']] = $tmAm_2;
                    $res[$k]['am_2'] = $tmAm_2;
                }
                
                if(isset($amArr[$tmpData['am_id_3']])){
                    $res[$k]['am_3'] = $amArr[$tmpData['am_id_3']];
                }
                else{
                    $sql = "select am_name from ".DB::table('area_main')." where am_id = '".$tmpData['am_id_3']."' ";
                    $tmAm_3 = DB::result_first($sql);
                    
                    $amArr[$tmpData['am_id_3']] = $tmAm_3;
                    $res[$k]['am_3'] = $tmAm_3;
                }
                
                if(isset($schoolArr[$tmpData['sm_id']])){
                    $res[$k]['sm_name'] = $schoolArr[$tmpData['sm_id']];
                }
                else{
                    $sql = "select sm_name from ".DB::table('school_main')." where sm_id = '".$tmpData['sm_id']."' ";
                    $tmSm = DB::result_first($sql);
                    
                    $schoolArr[$tmpData['sm_id']] = $tmSm;
                    $res[$k]['sm_name'] = $tmSm;
                }
                
                if(isset($classArr[$tmpData['class_id']])){
                    $res[$k]['class_name'] = $classArr[$tmpData['class_id']];
                }
                else{
                    $sql = "select class_name from ".DB::table('class_main')." where class_id = '".$tmpData['class_id']."' ";
                    $tmCm = DB::result_first($sql);
                    
                    $classArr[$tmpData['class_id']] = $tmCm;
                    $res[$k]['class_name'] = $tmCm;
                }
            }
        }
        
        //开始组装目标数组
        $filename = 'xktj'.date('YmdHis').'.csv'; //设置文件名
        $f = ',';//定义分隔符
        $list[] = iconv("utf-8","gb2312",'学生姓名'.$f.'省'.$f.'市'.$f.'区县'.$f.'学校'.$f.'班级');

        //将上述结果集转换为目标数组
        if(!empty($res) && is_array($res)){
            foreach ($res as $item) {
                $list[] = iconv("utf-8","gb2312",$item['name'].$f.$item['am_1'].$f.$item['am_2'].$f.$item['am_3'].$f.$item['sm_name'].$f.$item['class_name']);
            }
        }
        
        $target = SITE_ROOT.'data/upload/';
        $fp = fopen($target.$filename, 'w');
        //向目标文件写入操作
        foreach ($list as $line) {
            fputcsv($fp, explode(',', $line));
        }

        fclose($fp);
        
        $return['code'] = '1';
        //检测是否对应已生成csv文件
        if(is_file($target.$filename)){
            //2017-6-6 11:51:34 此处将该csv文件上传到文件服务器，同时删除本地的文件
            $data = ['filedata'  =>  new CURLFile($target.$filename), 'dir' => '/'];
            $ch = curl_init();

            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            curl_setopt($ch, CURLOPT_URL, 'http://101.37.15.34/upload.php');
            curl_setopt($ch, CURLOPT_POST, true );
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

             $res = curl_exec($ch);
             curl_close($ch);

             //此处删除掉本地的文件
             @unlink($target.$filename);

             if($res == 'success'){//成功
                $return['code'] = '0';
                $return['data']['url'] = 'http://fstore.jxzhjy.com/data/upload/'.$filename;
             }
             else{//远程文件上传失败
                $return['code'] = '1';
                $return['data']= [];
             }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /**
    * 选课统计 趋势图
    */
    public function do_coursetrend(){
        global $_G;
        
        //此处接收传递的搜索条件
        $cs_am_id_1 = isset($_REQUEST['am_id_1']) && !empty($_REQUEST['am_id_1']) ? $_REQUEST['am_id_1'] : '';//省
        $cs_am_id_2 = isset($_REQUEST['am_id_2']) && !empty($_REQUEST['am_id_2']) ? $_REQUEST['am_id_2'] : '';//市
        $cs_am_id_3 = isset($_REQUEST['am_id_3']) && !empty($_REQUEST['am_id_3']) ? $_REQUEST['am_id_3'] : '';//县
        $cs_sm_id = isset($_REQUEST['sm_id']) && !empty($_REQUEST['sm_id']) ? $_REQUEST['sm_id'] : '';//学校
        $cs_class_id = isset($_REQUEST['class_id']) && !empty($_REQUEST['class_id']) ? $_REQUEST['class_id'] : '';//班级
        $cs_cm_id = isset($_REQUEST['cm_id']) && !empty($_REQUEST['cm_id']) ? $_REQUEST['cm_id'] : '';//课程编号 必填项
        $cs_cm_cate_id = isset($_REQUEST['cm_cate_id']) && !empty($_REQUEST['cm_cate_id']) ? $_REQUEST['cm_cate_id'] : '';//课程分类
        $cs_cm_grade_id = isset($_REQUEST['cm_grade_id']) && !empty($_REQUEST['cm_grade_id']) ? $_REQUEST['cm_grade_id'] : '';//年级属性
        $cs_cm_subject_id = isset($_REQUEST['cm_subject_id']) && !empty($_REQUEST['cm_subject_id']) ? $_REQUEST['cm_subject_id'] : '';//学科属性
        
        $cs_type = isset($_REQUEST['type']) && !empty($_REQUEST['type']) ? $_REQUEST['type'] : 0;//统计时间范围
        
        //如果没有传递进来要查询的课程编号
        if(!$cs_cm_id){
            $return['code'] = '1';
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        
        if($cs_am_id_1){//如果传递进来了 省份id 对应查询名称
            $info = $this->one_info('area_main', 'am_id', $cs_am_id_1);
        }
        
        if($cs_am_id_2){//如果传递进来了 市区id 对应查询名称
            $info = $this->one_info('area_main', 'am_id', $cs_am_id_2);
        }
        
        if($cs_am_id_3){//如果传递进来了 县区id 对应查询名称
            $info = $this->one_info('area_main', 'am_id', $cs_am_id_3);
        }
        
        if($cs_sm_id){//如果传递进来了 学校id 对应查询名称
            $info = $this->one_info('school_main', 'sm_id', $cs_sm_id);
        }
        
        if($cs_class_id){//如果传递进来了 班级id 对应查询名称
            $info = $this->one_info('class_main', 'class_id', $cs_class_id);
        }
        
        $stime = 0;
        $dateArr = [];
        
        if($cs_type == 1){//近7天 按天统计
            $stime = TIMESTAMP - 7 * 86400;
            
            for($i = $stime;$i <= TIMESTAMP;$i += 86400){
                $tmp = date('Y-m-d', $i);
                $dateArr[$tmp] = 0;
            }
            
        }
        elseif($cs_type == 2){//近三个月 按周统计
            $stime = TIMESTAMP - 90 * 86400;
            
            for($i = $stime;$i <= TIMESTAMP;$i += (86400 * 7)){
                $tmp = date('Y-m-W', $i);
                $dateArr[$tmp] = 0;
            }
        }
        elseif($cs_type == 3){//近一年 按月统计
            $stime = TIMESTAMP - 365 * 86400;
            
            for($i = $stime;$i <= TIMESTAMP;$i += (86400 * 30)){
                $tmp = date('Y-m', $i);
                $dateArr[$tmp] = 0;
            }
        }
        
        $whereSql = " and cs_cm_id = '".$cs_cm_id."' and ctime >= '".$stime."' ";
        
        if($cs_am_id_1){//传递进来了 省份
            $whereSql.= " and cs_am_id_1 = ".$cs_am_id_1." ";
            $flag = 2;
        }
        
        if($cs_am_id_2){//传递进来了 市
            $whereSql.= " and cs_am_id_2 = ".$cs_am_id_2." ";
            $flag = 3;
        }
        
        if($cs_am_id_3){//传递进来了 县
            $whereSql.= " and cs_am_id_3 = ".$cs_am_id_3." ";
            $flag = 4;
        }
        
        if($cs_sm_id){//传递进来了 学校
            $whereSql.= " and cs_sm_id = ".$cs_sm_id." ";
            $flag = 5;
        }
        
        if($cs_class_id){//传递进来了 班级
            $whereSql.= " and cs_class_id = ".$cs_class_id." ";
            $flag = 6;
        }
        
        if($cs_cm_cate_id){//如果传递进来了课程分类
            $whereSql.= " and cs_cm_cate_id = '".$cs_cm_cate_id."' ";
        }
        
        if($cs_cm_grade_id){//如果传递进来了年级属性
            $whereSql.= " and cs_cm_grade_id = '".$cs_cm_grade_id."' ";
        }
        
        if($cs_cm_subject_id){//如果传递进来了学科属性
            $whereSql.= " and cs_cm_subject_id = '".$cs_cm_subject_id."' ";
        }
        
        $queries = " cs_user_id as k, ctime ";
        
        $sql = "select ".$queries." from ".DB::table('course_statistics')." where 1 = 1 ".$whereSql;
        $res = DB::fetch_all($sql);
        
        //列表中需显示对应的名称
        if(!empty($res) && is_array($res)){
            foreach ($res as $k => $item) {
                if($cs_type == 1){//近7天 按天统计
                    $tmp = date('Y-m-d', $item['ctime']);
                    $dateArr[$tmp] += 1;
                }
                elseif($cs_type == 2){//近三个月 按周统计
                    $tmp = date('Y-m-W', $item['ctime']);
                    $dateArr[$tmp] += 1;
                }
                elseif($cs_type == 3){//近一年 按月统计
                    $tmp = date('Y-m', $item['ctime']);
                    $dateArr[$tmp] += 1;
                }
            }
        }
        
        $keyArr = array_keys($dateArr);
        $valArr = array_values($dateArr);
        
        if($cs_type == 2){//近三个月按周统计时取出后面的第几周
            foreach ($keyArr as $k => $item) {
                $tmpArr = explode('-', $item);
                $keyArr[$k] = $tmpArr[0].'-'.$tmpArr[1];
            }
        }
        
        $return['code'] = '0';
        $return['data'] = ['key' => $keyArr, 'val' => $valArr];
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
}
?>